// pages/byMonth/index.js
import { formatDate, formatYYYYMM } from '../../utils/util'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isExpense: 'true',
    isLoad: false,

    allData: [],

    searchDt: '',
    searchStartDt: '',
    searchEndDt: '',
    findList: [],
    totalMoney: 0,
    recordCount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isExpense: options.isExpense || 'true',
    })
    var d = new Date()
    let year = options.year || d.getFullYear()
    let month = options.month || d.getMonth()

    this.updateDate(year, month)
  },
  loadData: function () {
    this.setData({
      isLoad: true
    })
    app.post({
      action: 'getExpenseList',
      data: {
        isExpense: this.data.isExpense,
        type: '',
        startDt: this.data.searchStartDt,
        endDt: this.data.searchEndDt
      }
    }).then(res => {
      let count = 0, sum = 0
      res.data.forEach(item => {
        count++;
        item.money = (+item.money).toFixed(2)
        sum += +item.money
      })
      this.setData({
        isLoad: false,
        allData: res.data,
        findList: res.data,
        totalMoney: sum.toFixed(2),
        recordCount: count
      })
    }).catch(res => {
      this.setData({
        isLoad: false,
        allData: [],
        findList: [],
        totalMoney: 0,
        recordCount: 0
      })
    })
  },
  updateDate(year, month) {
    var d = new Date(year, +month)
    d.setDate(1)
    var startDt = formatDate(d)
    d.setDate(new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate())
    var endDt = formatDate(d)
    this.setData({
      searchStartDt: startDt,
      searchEndDt: endDt,
      searchDt: formatYYYYMM(d)
    })
    this.loadData()
  },
  preMonth: function (e) {
    var searchDt = this.data.searchDt.split('-')
    this.updateDate(searchDt[0], searchDt[1] - 2)
  },
  nextMonth: function (e) {
    var searchDt = this.data.searchDt.split('-')
    this.updateDate(searchDt[0], searchDt[1])
  },
  searchDateChange: function (e) {
    console.log(e)
    var d = e.detail.value.split('-')
    this.updateDate(d[0], +d[1] - 1)
  },
})